﻿using System.Linq;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Security;
using SusuCMS.Web.Areas.Admin.Models;

namespace SusuCMS.Web.Areas.Admin.Controllers
{
    public class AccountController : AdminControllerBase
    {
        public ActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            return View(model);
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Login", "Account");
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = UserRepository.FindAll().FirstOrDefault(i => i.UserName == model.UserName);
                if (user != null && Crypto.VerifyHashedPassword(user.Password, string.Concat(model.Password, user.Salt)))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("LoginError", "The user name or password is incorrect.");
                }
            }

            return View(model);
        }
    }
}
